package com.vessel.decoration.app.base;

import android.content.Context;
import android.text.TextUtils;

import com.jess.arms.base.BaseService;
import com.jess.arms.integration.IRepositoryManager;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.vessel.decoration.app.constant.SPConstant;
import com.vessel.decoration.app.data.api.service.CommonService;
import com.vessel.decoration.app.data.entity.UserInfoResponse;
import com.vessel.decoration.app.utils.HttpResultFunc;
import com.vessel.decoration.app.utils.Pulse;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

import static com.vessel.decoration.app.constant.Constants.EVENT_USERINFO;

/**
 * @author vesselzhang
 * @date 2017/12/13
 */

public class BackService extends BaseService {

    private Context context;

    private Pulse mPulse;
    private Thread mPulseThread;
    private Runnable[] runs;

    protected IRepositoryManager mRepositoryManager;

    @Override
    public void init() {
        context = getApplicationContext();
        mRepositoryManager = ArmsUtils.obtainAppComponentFromContext(context).repositoryManager();

        runs = new Runnable[]{
                new UserInfoRequest()
        };

        mPulse = new Pulse(runs);
        mPulseThread = new Thread(mPulse);
        mPulseThread.start();
    }

    @Subscriber(tag = EVENT_USERINFO)
    public void onRefresh() {
        new Thread(new UserInfoRequest()).start();
    }

    private class UserInfoRequest implements Runnable, Observer<UserInfoResponse> {

        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onNext(UserInfoResponse userInfoResponse) {
            DataHelper.saveDeviceData(context, SPConstant.SP_USERINFO, userInfoResponse);
            EventBus.getDefault().post(userInfoResponse);
        }

        @Override
        public void onError(Throwable e) {

        }

        @Override
        public void onComplete() {

        }

        @Override
        public void run() {
            String token = DataHelper.getStringSF(context, SPConstant.SP_TOKEN);
            if (TextUtils.isEmpty(token)) return;

            mRepositoryManager.obtainRetrofitService(CommonService.class)
                    .queryInfo()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .map(new HttpResultFunc<>())
                    .subscribe(this);
        }
    }
}
